﻿using System.IO;
using System.Net;
using System.Net.Sockets;
using System;

using Utilities.IO;

namespace Utilities.Net
{
    public class TcpStream : Stream
    {
        protected TcpClient tcpClient;
        protected NetworkStream networkStream;

        public IPEndPoint LocalEndPoint
        {
            get
            {
                return tcpClient.Client.LocalEndPoint as IPEndPoint;
            }
        }
        public IPEndPoint RemoteEndPoint
        {
            get
            {
                return tcpClient.Client.RemoteEndPoint as IPEndPoint;
            }
        }

        public bool Connected
        {
            get
            {
                return tcpClient.Connected;
            }
        }

#if DEBUG
        public QueueStream DebugStream { get; private set; }
        public byte[] DebugBuffer
        {
            get
            {
                return DebugStream.Buffer.ToArray();
            }
        }
        public string DebugBufferString
        {
            get
            {
                return DebugStream.Buffer.ToArray().ToHexString(' ');
            }
        }

        private byte[] debugByte = new byte[] { 0 };
#endif

        public TcpStream(string hostname, int port) : this(new TcpClient(hostname, port))
        {
        }
        public TcpStream(IPAddress address, int port) : this(new TcpClient(new IPEndPoint(address, port)))
        {
        }
        public TcpStream(TcpClient client)
        {
            Disconnect += Disconnect_DefaultHandler;

            tcpClient = client;
            networkStream = client.GetStream();

#if DEBUG
            DebugStream = new QueueStream();
            networkStream.BeginRead(debugByte, 0, 1, new AsyncCallback(Debug_ReadAsync), null);
#endif
        }

        public override bool CanRead
        {
            get
            {
                return networkStream.CanRead;
            }
        }
        public override bool CanWrite
        {
            get
            {
                return networkStream.CanWrite;
            }
        }
        public override bool CanSeek
        {
            get
            {
                return networkStream.CanSeek;
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            int read = 0;
            try
            {
#if DEBUG
                read = DebugStream.Read(buffer, offset, count);
#else
                read = networkStream.Read(buffer, offset, count);
#endif
            }
            catch (IOException e)
            {
                if (Disconnect != null)
                    Disconnect(this);
            }
            return read;
        }
        public override void Write(byte[] buffer, int offset, int count)
        {
            try
            {
                networkStream.Write(buffer, offset, count);
            }
            catch (IOException e)
            {
                if (Disconnect != null)
                    Disconnect(this);
            }
        }
        public override long Seek(long offset, SeekOrigin origin)
        {
            // TODO: Error handling
            return networkStream.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            networkStream.SetLength(value);
        }
        public override void Flush()
        {
            networkStream.Flush();
        }
        public override long Length
        {
            get
            {
                return networkStream.Length;
            }
        }
        public override long Position
        {
            get
            {
                return networkStream.Position;
            }
            set
            {
                networkStream.Position = value;
            }
        }

        public override void Close()
        {
            networkStream.Close();
            base.Close();
        }

        private void Disconnect_DefaultHandler(TcpStream stream)
        {
            //throw new SocketException(-1);
        }

        public delegate void TcpStreamDisconnectEventHandler(TcpStream stream);
        public event TcpStreamDisconnectEventHandler Disconnect;

#if DEBUG
        private void Debug_ReadAsync(IAsyncResult asyncResult)
        {
            int count = networkStream.EndRead(asyncResult);
            if (count != 1)
                return;

            DebugStream.WriteByte(debugByte[0]);
            networkStream.BeginRead(debugByte, 0, 1, new AsyncCallback(Debug_ReadAsync), null);
        }
#endif
    }
}